<?php

namespace app\company\controller\message\push;

use app\BaseController;
use app\model\MessageModel;
use app\model\platform\PlatformPushMessageModel;
use app\model\UserModel;
use app\socket\Server;
use think\App;
use think\facade\Queue;
use think\swoole\Websocket;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }


    /**
     * 推送消息
     * @param Websocket $websocket
     * @return bool|string
     */
    public function PushMessage(Websocket $websocket): bool|string
    {
        $PlatformPushMessageModel = new PlatformPushMessageModel();
        $PlatformPushMessageModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'unit_id|单位' => 'require',
                'content|内容'  =>  'require',
                'is_time|时间'  =>  'require',
                'channel|推送渠道'  =>  'require',
            ]);
            $time = time();
            $remaining_time = $param['time']??0 - $time;
            //推送socket消息
            $socketServer = new Server();
            if (!$param['is_time'] || $remaining_time <= 0){
                $PlatformPushMessageModel->insert([
                    'company_id' => $this->userData['company_id'],
                    'areas_id' => $this->userData['areas_id'],
                    'uid' => $this->userData['id'],
                    'unit_id' => implode(',',$param['unit_id']),
                    'channel' => implode(',',$param['channel']),
                    'content' => $param['content'],
                    'is_time' => $param['is_time'],
                    'send_time' => $param['send_time']??0,
                    'status' => 1,
                    'time' => $time,
                ]);
                $UserModel = new UserModel();
                $MessageModel = new MessageModel();
                $uids = $UserModel->where([
                    ['unit_id','in',$param['unit_id']],
                    ['role_mode','=',3]
                ])->column('id');
                $MessageData = [];
                foreach ($uids as $uid) {
                    $MessageAddData = [
                        'uid' => $uid,
                        'type' => 23,
                        'title' => '系统推送',
                        'content' => $param['content'],
                        'time' => time()
                    ];
                    $MessageData[] = $MessageAddData;
//                    cache()->rpush(env('REDIS_PROJECT').'message_push',json_encode($MessageAddData,true));
                }
                $fd = $socketServer->uidGetFd($uids);
                $socketSendData = [
                    'type' => 'message',
                    'content' => [
                        'type' => 23,
                        'title' => '系统推送',
                        'content' => $param['content'],
                        'img' => match (23){
                            3,4,5,7,8,9,10 => '/icon_task/202411/07_1730960087672c5ad715646.png',//测评任务消息
                            6,11, 1, 2, 14, 15, 16,23 => '/icon_task/202411/07_1730960430672c5c2ee2c98.png',//预警报告消息-系统通知-公告-危机干预
                            17 => '/icon_task/202411/07_1730944047672c1c2fd624c.png',//预约咨询消息
                            22 => '/icon_task/202411/07_1730941588672c1294c2e1e.png',//物联网消息
                        },
                        'time' => time()
                    ]
                ];
                $MessageModel->insertAll($MessageData);
            }else{
                $id = $PlatformPushMessageModel->insertGetId([
                    'company_id' => $this->userData['company_id'],
                    'areas_id' => $this->userData['areas_id'],
                    'uid' => $this->userData['id'],
                    'unit_id' => implode(',',$param['unit_id']),
                    'channel' => implode(',',$param['channel']),
                    'content' => $param['content'],
                    'is_time' => $param['is_time'],
                    'send_time' => $param['send_time']??0,
                    'status' => 0,
                    'time' => $time,
                ]);
                if (!Queue::later($remaining_time,\app\job\CronJob::class, [
                    'method' => 'PlatformPushMessage',
                    'data' => [
                        'message_id' => $id
                    ],
                ], 'CronJob'))
                    throw new \Exception('队列创建失败！');
            }
            $PlatformPushMessageModel->commit();
            if (!empty($fd) && !empty($socketSendData)){
                $socketServer->push($fd,json_encode($socketSendData),$websocket);
            }
            return success([],'推送成功！');
        } catch (\Exception $e) {
            $PlatformPushMessageModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 推送历史记录
     * @return bool|string
     */
    public function PushMessageList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示的数量' => 'require',
            ]);
            $where[] = ['company_id','=',$this->userData['company_id']];
            $where[] = ['areas_id','=',$this->userData['areas_id']];
            $PlatformPushMessageModel = new PlatformPushMessageModel();
            $data = $PlatformPushMessageModel->where($where)->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['unit_id'] = explode(',',$item['unit_id']);
                $item['channel'] = explode(',',$item['channel']);
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 推送历史记录-删除
     * @return bool|string
     */
    public function PushMessageDel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $PlatformPushMessageModel = new PlatformPushMessageModel();
            $info = $PlatformPushMessageModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}